package com.my.algorithmlearning.leetcode;

/**
 * @ClassName Medium_279_PerfectSquares_DynamicProgramming
 * @Description Medium_279_PerfectSquares_DynamicProgramming
 * @Author wanghaiwei
 * @Date 2023/7/14 16:04
 */
public class Medium_279_PerfectSquares_DynamicProgramming {
    public int numSquares(int n) {
        if (n <= 3) {
            return n;
        }
        int bigestSqrtRoot = (int) Math.sqrt(n);
        if (bigestSqrtRoot * bigestSqrtRoot == n) {
            return 1;
        }
        int[] dp = new int[n + 1];
        dp[0] = 0;
        dp[1] = 1;
        dp[2] = 2;
        dp[3] = 3;
        for (int i = 4; i < n + 1; i++) {
            dp[i] = i;
        }
        for (int i = 1; i < n + 1; i++) {
            for (int j = 1; j <= i / 2; j++) {
                if (j * j == i) {
                    dp[i] = 1;
                    break;
                }
                dp[i] = Math.min(dp[i], dp[j] + dp[i - j]);
            }
        }
        return dp[n];
    }

    public static void main(String[] args) {
        Medium_279_PerfectSquares_DynamicProgramming perfectSquares = new Medium_279_PerfectSquares_DynamicProgramming();
        System.out.println(perfectSquares.numSquares(12));
        System.out.println(perfectSquares.numSquares(13));
    }
}
